package me.boot.db.mybatis.handler;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import me.base.utils.DebugUtil;
import me.boot.common.constant.DbConst;
import me.boot.common.context.ContextUtil;
import me.boot.common.data.model.UserInfo;
import me.boot.db.mybatis.template.entity.Entity;
import me.boot.db.mybatis.template.pojo.EntityCreater;
import me.boot.db.mybatis.template.pojo.EntityOwner;
import me.boot.db.mybatis.template.pojo.EntityUpdater;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * 自动填充时间字段
 */
@Slf4j
@Component
public class AutoMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (!isEntity(metaObject) || !openInsertFill()) {
            return;
        }
        log.debug("插入时，自动填充...");
        this.strictInsertFill(metaObject, DbConst.PROPERTY_OWNER, EntityOwner.class, getOwner());
        this.strictInsertFill(metaObject, DbConst.PROPERTY_CREATER, EntityCreater.class, getCreater());
        this.strictInsertFill(metaObject, DbConst.PROPERTY_UPDATER, EntityUpdater.class, getUpdater());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (!isEntity(metaObject) || !openUpdateFill()) {
            return;
        }

        log.debug("更新时，自动填充...");
        this.strictUpdateFill(metaObject, DbConst.PROPERTY_UPDATER, EntityUpdater.class, getUpdater());
    }

    private EntityOwner getOwner() {
        UserInfo user = getUserInfo();
        EntityOwner foo = new EntityOwner();
        BeanUtil.copyProperties(user, foo, true);
        return foo;
    }

    private EntityCreater getCreater() {
        UserInfo user = getUserInfo();
        EntityCreater foo = new EntityCreater();
        foo.setId(user.getUserId());
        foo.setName(user.getUserName());
        return foo;
    }

    private EntityUpdater getUpdater() {
        UserInfo user = getUserInfo();
        EntityUpdater foo = new EntityUpdater();
        foo.setId(user.getUserId());
        foo.setName(user.getUserName());
        return foo;
    }

    private UserInfo getUserInfo() {
        UserInfo user = ContextUtil.getUser();
        if (user == null && DebugUtil.isDebug()) {
            user = new UserInfo();
            user.setTenantId(1L);
            user.setTenantName("TEST_TENANT");
            user.setCompanyId(1L);
            user.setCompanyName("TEST_COMPANY");
            user.setDepartmentId(1L);
            user.setDepartmentName("TEST_DEPARTMENT");
            user.setUserId(1L);
            user.setUserName("TEST_USER");
        }
        return user;
    }

    private static boolean isEntity(MetaObject metaObject) {
        return metaObject.getOriginalObject() instanceof Entity;
    }

}
